<template>
  <section class="add">
    <el-form ref="formRef" :model="form" label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="form.studentName"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="form.sex"></el-input>
      </el-form-item>
      <el-form-item label="学院">
        <el-input v-model="form.institute"></el-input>
      </el-form-item>
      <el-form-item label="所属专业">
        <el-input v-model="form.major"></el-input>
      </el-form-item>
      <el-form-item label="年级">
        <el-input v-model="form.grade"></el-input>
      </el-form-item>
      <el-form-item label="班级">
        <el-input v-model="form.clazz"></el-input>
      </el-form-item>
      <el-form-item label="电话号码">
        <el-input v-model="form.tel"></el-input>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="form.cardId"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button type="text" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
import { ref, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';

export default {
  setup() {
    const form = ref({
      studentName: '',
      sex: '',
      institute: '',
      major: '',
      grade: '',
      clazz: '',
      tel: '',
      cardId: '',
      email: '',
      pwd: '',
      role: 2,
    });

    const formRef = ref(null);
    const router = useRouter();
    const { proxy } = getCurrentInstance(); // 关键点：获取全局属性

    const onSubmit = async () => {
      try {
        const res = await proxy.$axios.post('/api/student', form.value);
        if (res.data.code === 200) {
          proxy.$message.success('数据添加成功');
          router.push('/index/studentManage');
        } else {
          proxy.$message.error(res.data.message || '添加失败');
        }
      } catch (err) {
        console.error(err);
        proxy.$message.error('请求出错');
      }
    };

    const cancel = () => {
      formRef.value.resetFields();
    };

    return {
      form,
      formRef,
      onSubmit,
      cancel,
    };
  },
};
</script>

<style scoped lang="less">
.add {
  padding: 0 40px;
  width: 400px;
}
</style>
